package com.vy.stl.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.vy.stl.constants.Constants;
import com.vy.stl.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @create: 2025/09/10 21:04
 * @description:
 */
@RestController
@RequestMapping("/upload")
public class FileController {
    @Value("${alinfo.oss-bucketname}")
    private String bucketName;
    @Value("${alinfo.oss-endpoint}")
    private String endpoint;
    @Value("${alinfo.oss-accesskeyid}")
    private String accessKeyId;
    @Value("${alinfo.oss-accesskeysecret}")
    private String accessKeySecret;

    @RequestMapping("/savePic")
    public Result savePic(@RequestParam("file") MultipartFile file) {// 1.接收前端表单中name="file"的文件，2.MultipartFile：处理文件上传的接口
        //获取上传文件的原始文件名
        String filename = file.getOriginalFilename(); // lyx01.jpg
        // 生成通用唯一识别码，去掉中间的横线
        String uuidStr = UUID.randomUUID().toString().replace("-","");
        System.out.println(uuidStr); //71201a0d66354150b4b0b0455861ce7a
        // 提取文件的扩展名
        filename = filename.substring(filename.lastIndexOf(".")); //.jpg
        // 拼接成新的唯一文件名
        String newFileName = uuidStr + filename;

        // 构建阿里云OSS的存储路径
        String objectName = "viola/"+newFileName;

        /* 上传文件到阿里云OSS */
        // 创建阿里云OSS客户端对象，需要导入oss依赖
        OSS ossClient = null;
        try {
            // 初始化OSS客户端（OSS服务的地域节点，阿里云账号的访问密钥）
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件到 OSS
            ossClient.putObject(bucketName, objectName, file.getInputStream());
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            ossClient.shutdown();
        }
        // 构建头像的访问路径
        String path = "https://zxst-shoop-822.oss-cn-qingdao.aliyuncs.com/" + objectName;

        return Result.success(Constants.STATUS_200,null,path);
    }
}
